# -*- coding: utf-8 -*-
"""
商品控制层

负责处理商品相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Optional, List
from app.services.goods_service import GoodsService

router = APIRouter(
    prefix="/goods",
    tags=["goods"],
    responses={404: {"description": "Not found"}}
)

# 初始化服务层
goods_service = GoodsService()

# Pydantic 模型
class BannerResponse(BaseModel):
    id: int = Field(..., description="轮播图ID")
    title: str = Field(..., description="轮播图标题")
    image: str = Field(..., description="轮播图图片URL")
    link_type: str = Field(..., description="链接类型：goods商品、category分类、url外链")
    link_value: str = Field(..., description="链接值")
    sort: int = Field(..., description="排序")
    status: int = Field(..., description="状态")

class CategoryResponse(BaseModel):
    class_id: str = Field(..., description="分类ID")
    pareant_id: Optional[str] = Field(None, description="父分类ID")
    is_leaf: Optional[str] = Field(None, description="是否叶子节点")
    class_name: str = Field(..., description="分类名称")
    path: Optional[str] = Field(None, description="分类路径")
    icon: Optional[str] = Field(None, description="分类图标")
    gradient: Optional[str] = Field(None, description="渐变色")
    goods_count: Optional[int] = Field(None, description="商品数量")


@router.get("/banners")
async def get_banners(
    status: Optional[int] = Query(1, description="状态筛选：1启用，0禁用"),
    limit: int = Query(10, gt=0, le=50, description="返回数量限制")
):
    """获取轮播图列表"""
    try:
        result = goods_service.get_banners(status=status, limit=limit)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取轮播图失败: {str(e)}")


@router.get("/list")
async def get_goods_list(
    include_specs: bool = Query(False, description="是否包含规格信息"),
    include_sales: bool = Query(True, description="是否包含销售统计"),
    page: int = Query(1, gt=0),
    pageSize: int = Query(10, gt=0, le=100),
    sort: Optional[str] = "default",
    priceAsc: bool = Query(False, description="价格正序"),
    salesAsc: bool = Query(False, description="销售额正序"),
    keyword: Optional[str] = None,
    categoryId: Optional[str] = None
):
    """获取商品列表"""
    try:
        result = goods_service.get_goods_list(
            include_specs=include_specs,
            include_sales=include_sales,
            page=page,
            page_size=pageSize,
            sort=sort,
            price_asc=priceAsc,
            sales_asc=salesAsc,
            keyword=keyword,
            categoryId=categoryId
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/detail/{goods_id}")
async def get_goods_detail(
    goods_id: str,
    include_sales: bool = Query(True, description="是否包含销售统计"),
    include_comments: bool = Query(True, description="是否包含评论统计")
):
    """获取商品详情"""
    try:
        result = goods_service.get_goods_detail(
            goods_id, 
            include_sales=include_sales, 
            include_comments=include_comments
        )
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/specs/{goods_id}")
async def get_goods_specs(
    goods_id: str,
    include_barcodes: bool = Query(True, description="是否包含条形码信息")
):
    """获取商品规格列表"""
    try:
        result = goods_service.get_goods_specs(goods_id, include_barcodes)
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/barcode/{barcode}")
async def get_goods_by_barcode(barcode: str):
    """通过条码查询商品"""
    try:
        result = goods_service.get_goods_by_barcode(barcode)
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/comments/{goods_id}")
async def get_goods_comments(
    goods_id: str,
    page: int = Query(1, gt=0),
    pageSize: int = Query(10, gt=0, le=100)
):
    """获取商品评论列表"""
    try:
        result = goods_service.get_goods_comments(goods_id, page, pageSize)
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/brands")
async def get_brands(
    brand_name: Optional[str] = None,
    page: int = Query(1, gt=0),
    page_size: int = Query(10, gt=0, le=100)
):
    """获取品牌列表"""
    try:
        result = goods_service.get_brands(brand_name, page, page_size)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/categories")
async def get_categories(
    class_name: Optional[str] = Query(None, description="分类名称搜索"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量"),
    include_goods_count: bool = Query(False, description="是否包含商品数量")
):
    """获取分类列表"""
    try:
        result = goods_service.get_categories(
            class_name=class_name,
            page=page,
            page_size=page_size,
            include_goods_count=include_goods_count
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取分类列表失败: {str(e)}")


@router.get("/categories/all")
async def get_all_categories(
    include_goods_count: bool = Query(False, description="是否包含商品数量")
):
    """获取所有分类（用于构建树形结构）"""
    try:
        result = goods_service.get_all_categories(include_goods_count=include_goods_count)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取所有分类失败: {str(e)}") 